package com.cmq.web_1.error;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebServlet(name = "ErrorHandlingDemoServlet", urlPatterns = {"/demo/error"})
public class ErrorHandlingDemoServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String action = request.getParameter("action");

        try {
            if ("error404".equals(action)) {
                // 模拟404错误
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "自定义404错误信息");
            }
            else if ("error500".equals(action)) {
                // 模拟500错误
                throw new ServletException("模拟服务器内部错误");
            }
            else if ("invalidParam".equals(action)) {
                // 模拟参数错误
                String id = request.getParameter("id");
                if (id == null || id.trim().isEmpty()) {
                    // 设置错误信息并转发到400页面
                    request.setAttribute("errorMessage", "ID参数不能为空");
                    request.getRequestDispatcher("/error/400.jsp").forward(request, response);
                    return;
                }
            }
            else {
                response.getWriter().println("正常访问页面");
            }
        }
        catch (Exception e) {
            // 捕获所有异常，设置错误信息并转发到500页面
            request.setAttribute("errorMessage", e.getMessage());
            request.setAttribute("jakarta.servlet.error.exception", e); // 与默认错误属性保持一致
            request.getRequestDispatcher("/error/500.jsp").forward(request, response);
        }
    }
}
